package com.deng.crowd.mvc.handler;

import com.deng.crowd.constant.CrowdConstant;
import com.deng.crowd.entity.Admin;
import com.deng.crowd.exception.AccessForbidden;
import com.deng.crowd.service.api.AdminService;
import com.deng.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.List;

@Controller
public class AdminHandler {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/admin/do/login.html")
    public String doLogin(
            @RequestParam("loginAcct") String loginAcct,
            @RequestParam("userPswd") String userPswd,
            HttpSession session
        ) {
        // 1.调用service方法执行登录检查
        // 返回admin对象说明登录成功，否则会抛出异常
        Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);

        // 2.将登录成功返回的admin对象存入Session域
        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);
        return "redirect:/admin/main/page.html";
    }
    @RequestMapping(value = "/admin/do/logout.html")
    public String doLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/admin/to/login.html";
    }

    @RequestMapping(value = "/admin/get/page.html")
    public String getPageInfo(
            // 传入的关键字，若未传入，默认值为一个空字符串（不能是null）
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            // 传入的页码，默认值为1
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            // 传入的页面大小，默认值为5
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            // ModelMap用于给前端带数据
            Model model
    ) {
        PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);
        model.addAttribute(CrowdConstant.ATTR_NANE_PAGE_INFO, pageInfo);
        return "admin-page";
    }

    @RequestMapping("/admin/remove/{adminId}/{pageNum}/{keyword}.html")
    public String removeAdmin(
            // 从前端获取的管理员id
            @PathVariable("adminId") Integer adminId,
            // 从前端获取的当前页码与关键字（为了删除后跳转的页面仍然是刚才的页面，优化体验）
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("keyword") String keyword,
            // HttpSession session
            Principal principal) {
        Admin admin = new Admin();
        // admin = (Admin)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
        String name = principal.getName();
        admin = adminService.getAdminByLoginAcct(name);
        System.out.println(principal);
        if(adminId.equals(admin.getId())) {
            throw new AccessForbidden("不能删除自己的账户!");
        }
        // 调用service层方法，从数据库根据id删除管理员
        adminService.removeById(adminId);
        //删除完成后，重定向（减少数据库操作）返回信息页
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

    @PreAuthorize("hasAuthority('user:save')")
    @RequestMapping(value="/admin/page/doAdd.html")
    public String addAdmin(Admin admin) {
        // 调用service层存储admin对象的方法
        adminService.saveAdmin(admin);
        // 重定向回原本的页面，且为了能在添加管理员后看到管理员，设置pageNum为整型的最大值（通过修正到最后一页）
        return "redirect:/admin/get/page.html?pageNum="+Integer.MAX_VALUE;
    }

    @RequestMapping("/admin/update/{adminId}/{pageNum}/{keyword}.html")
    public String toUpdatePage(
            @PathVariable("adminId") Integer adminId,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("keyword") String keyword,
            Model model) {
        Admin admin = adminService.queryAdmin(adminId);
        model.addAttribute("admin", admin);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("keyword", keyword);
        return "admin-update";
    }

    @RequestMapping("/admin/page/doUpdate.html")
    public String updateAdmin(Admin admin, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam("keyword") String keyword) {
        // 调用service层 updateAdmin方法
        adminService.updateAdmin(admin);
        // 正常执行则进入原先的管理员信息页面
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

    @ResponseBody
    @RequestMapping("admin/remove/by/admin/id/array.json")
    public ResultEntity<String> removeByAdminIdArray(@RequestBody List<Integer> adminIdList) {
        adminService.removeAdmin(adminIdList);
        return ResultEntity.successWithoutData();
    }
}